<?php
namespace App\V3\Api\Services;

use App\V3\Api\Models\AdminAddendumModel;
use App\V3\Api\Models\VipOrderModel;
use App\V3\Api\Models\VipSettingModel;
use  App\V3\Api\Models\AdminModel;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\V3\Api\Models\BuyStorageSpaceModel;
use App\V3\Api\Models\StorageSpaceOrderModel;


class OrderService
{
    public static function generateSn(){
        $date = Carbon::now('Asia/Shanghai');
        $rnd = rand(100000,999999);
        return $date->format('YmdHisu').$rnd;
    }

     public static  function ssGenerateSn(){
        $date = Carbon::now('Asia/Shanghai');
        $rnd = rand(100000,999999);
        return 'KJ'.$date->format('YmdHisu').$rnd;
    }

    public static function getWechatConfig()
    {
        return [
            'app_id' => config('app.miniapp_id'),
            'mch_id' => config('app.wechat_mch_id'),
            'key' => config('app.wechat_key'),
            'notify_url' => config('app.wechat_notify_url').'wechat_order_notify',
            //'sanbox' => true //沙箱模式打开或关闭
        ];
    }

    public static function getAPPWechatConfig()
    {
        return [
            'app_id' => config('app.appapp_id'),
            'mch_id' => config('app.wechat_mch_id'),
            'key' => config('app.wechat_key'),
            'notify_url' => config('app.wechat_notify_url').'wechat_order_notify',
            //'sanbox' => true //沙箱模式打开或关闭
        ];
    }
    public static function getVipSetting($id)
    {
        return VipSettingModel::select('open_vip_cost')
           ->where([
               'id' => $id,
           ])->first();
    }

    public static function payByWechat($mainId,$order_sn,$data)
    {
        if(strpos($order_sn, 'KJ')!==false){
            //购买存储空间
            $order = StorageSpaceOrderModel::select('type','price')->where('order_sn',$order_sn)->first();
        }else{
            //VIP充值
            $order = VipOrderModel::select('*')->where([
                'order_sn' => $order_sn
            ])->first();
        }
        if(empty($order)){
            return ['code' => 1, 'msg' => '订单创建失败', 'data' => ''];
        }

        switch ($order['type']){
            case 1:
                $body = 'VIP充值';
                break;
            case 2:
                $body = '购买存储空间';

                break;
            default:
                return ['code' => 1, 'msg' => '订单错误', 'data' => ''];
        }

        $total_fee = $order['price']*100;

        //获取openid 如果传code 请求微信接口  不传 查询数据库
        if(!empty($data['code']) && $data['pay_type'] != 2){
            $wxinfo = json_decode(LoginService::getOpenId($data['code']), true);
            $open_id = $wxinfo['openid'];
        }else{
            $admin = AdminModel::where('id', $mainId)->first();
            $open_id = $admin['openid'];
        }
        if($data['pay_type'] ==2){
            $payment = Factory::payment(self::getAPPWechatConfig());
        }else{
            $payment = Factory::payment(self::getWechatConfig());
        }

        $jssdk = $payment->jssdk;

        switch ($data['pay_type']){
            case 1:
                //小程序
                $res = $payment->order->unify([
                    'app_id' => config('app.wepay_mini_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'JSAPI',
                    'openid' => $open_id,
                    'notify_url' => config('app.wechat_notify_url').'wechat_order_notify',
                ]);
                break;
            case 2:
                //app
                $res = $payment->order->unify([
                    'app_id' => config('app.app_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'APP',
                    /* 'openid' => $open_id, */
                    'notify_url' => config('app.wechat_notify_url').'wechat_order_notify',
                ]);
                break;
            default:
                $res = $payment->order->unify([
                    'app_id' => config('app.wechat_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'JSAPI',
                    'openid' => $open_id,
                    'notify_url' => config('app.wechat_notify_url').'wechat_order_notify',
                ]);
        }

        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            $prepay_id = $res['prepay_id'];

            switch ($data['pay_type']){
                case 1:
                    //小程序
                    $config = $jssdk->sdkConfig($prepay_id);
                    #$config = $jssdk->bridgeConfig($prepay_id); //json形式
                    break;
                case 2:
                    //app
                    $config = $jssdk->appConfig($prepay_id);
                    break;
                default:
                    $config = $jssdk->sdkConfig($prepay_id);
            }
            return ['code' => 0, 'msg' => '创建订单成功', 'data' => $config];

        }


        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL'){

            return ['code' => 0, 'msg' => '微信支付失败', 'data' => $res['err_code_des']];

        }

        if($res['return_code'] == 'FAIL' && array_key_exists('return_msg',$res)){

            return ['code' => 0, 'msg' => '微信支付失败', 'data' => $res['err_code_des']];
        }

    }


    public static function createOrder($mainId,$data)
    {
        if($data['type']==2){
            //创建购买存储空间的订单号
            $order_sn = self::ssGenerateSn();
        }else{
            //创建购买VIP的订单号
            $order_sn = self::generateSn();
        }

        $res = '';

        switch ($data['type']){
            case 1:
                self::createVipOrder($order_sn,$mainId,$data);
                break;
            case 2:
                //购买存储空间
                self::createStorageSpaceOrder($order_sn,$mainId, $data);
                break;
            default:
                self::createVipOrder($order_sn,$mainId,$data);
        }

        //微信支付
        if(in_array($data['pay_type'],[1,2])){
            $res = self::payByWechat($mainId,$order_sn,$data);
        }

        return $res;
    }

    //创建VIP订单
    public static function createVipOrder($order_sn,$mainId,$data)
    {
        $setting_info = VipSettingModel::select('*')
            ->where('is_vip',1)
            ->orderBy('id', 'desc')->first();

        //判断用户是否首充
        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $mainId])->first()->toArray();

        if(empty($addendum_data['is_first_charge'])){
            //首充
            $price = $setting_info['first_charge_price'];
        }else{
            //非首充
            $price = $setting_info['open_vip_cost'];
        }

        VipOrderModel::updateOrCreate([
            'order_sn' => $order_sn,
        ],[
            'order_sn' => $order_sn,
            'main_id' => $mainId,
            'price' => $price,
            'type' => $data['type'],
            'album_amount' => $setting_info['album_amount'],
            'album_page_amount' => $setting_info['album_page_amount'],
            'empty_bill_amount' => $setting_info['empty_bill_amount'],
            'special_seal' => $setting_info['special_seal'],
            'one_key_album_times' => $setting_info['one_key_album_times'],
            'express_check_times' => $setting_info['express_check_times'],
            'account_storage' => $setting_info['account_storage'],
            'clear_watermark_or_not	' => $setting_info['clear_watermark_or_not'],
        ]);
    }
    //购买存储空间
    public static function createStorageSpaceOrder($order_sn,$mainId,$data)

    {
        $info = BuyStorageSpaceModel::find($data['space_id']);

        StorageSpaceOrderModel::updateOrCreate([
            'order_sn' => $order_sn,
        ],[
            'order_sn' => $order_sn,
            'main_id' => $mainId,
            'price' => $info['price'],
            'buy_storage_space' => $info['set_space'],
            'pay_type' => $data['pay_type'],
        ]);
    }

    //订单回调
    public static function notifyByWeChat($fields)
    {Log::info('回调参数：', $fields);
       // $order = VipOrderModel::select('pay_type')->where('order_sn', $fields['out_trade_no'])->first();

        $config = self::getWechatConfig();



        $payment = Factory::payment($config);

        $response = $payment->handlePaidNotify(function ($message, $fail) use ($fields) {


            if(strpos($message['out_trade_no'], 'KJ')!==false){
                //购买存储空间
                $order = StorageSpaceOrderModel::where('order_sn',$message['out_trade_no'])
                        ->get()->toArray();
            }else{
                //VIP充值
                // 根据返回的订单号查询订单数据
                $order = VipOrderModel::where('order_sn', $message['out_trade_no'])->get()->toArray();
            }

            if (!$order) {
                $fail('订单不存在!');
            }
            $order = reset($order);

            if ($order['status'] == '1') {
                return true;
            }

            // 支付成功后的业务逻辑
            if ($message['result_code'] === 'SUCCESS') {
                Log::info('支付成功 开始操作数据库');

                $order['order_sn'] = $message['out_trade_no']; // 回调订单号
                $order['out_order_sn'] = $message['transaction_id']; // 回调流水号
                $order['pay_time'] = time();
                $order['status'] = 1;

                DB::beginTransaction();

                try {
                    Log::info('开始更新订单表');
                    if(strpos($message['out_trade_no'], 'KJ')!==false){

                        StorageSpaceOrderModel::updateOrCreate([
                            'order_sn' => $order['order_sn'],
                        ],$order);
                        Log::info('开始更新admin_addendum表');
                        self::updateAddendum($order['main_id'],$order);

                    }else{
                        VipOrderModel::updateOrCreate([
                            'order_sn' => $order['order_sn'],
                        ],$order);

                        #VipOrderModel::where('order_sn', $order['order_sn'])->update($order);
                        Log::info('开始更新admin_addendum表');
                        self::updateAddendum($order['main_id'],$order);
                    }
                    DB::commit();
                    Log::info('更新完成');

                    return true;
                } catch (\Exception $e) {
                    Log::info('更新失败'.var_export($e->getMessage(), true));

                    DB::rollBack();
                }
            }

            return true;
        });

        return $response;
    }

    public static function updateAddendum($main_id,$order_data)
    {
        $order_type = $order_data['type'];

        switch ($order_type){
            case 1:
                //vip
                return self::updateVipAddendum($main_id,$order_data);
                break;
            case 2:
                //购买空间
                return self::updateSpaceOrderAddendum($main_id,$order_data);
                break;
            default:
                return false;
        }

    }

    public static function updateVipAddendum($main_id,$order_data)
    {
        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $main_id])->first()->toArray();

        $vip_time = 365*24*3600;

        $setting_data = VipSettingModel::select('*')
            ->where('is_vip',1)
            ->orderBy('id', 'desc')->first();

        if(empty($addendum_data)){
            $vip_end_date = $order_data['pay_time'] + $vip_time;
        }else{
            if(time() > strtotime($addendum_data['vip_end_date'])){
                //会员过期
                $vip_end_date = $order_data['pay_time'] + $vip_time;
            }else{
                $vip_end_date = strtotime($addendum_data['vip_end_date']) + $vip_time;
            }
        }

        $is_vip = 1;

        $is_share_customer = empty($addendum_data)? 0 : $addendum_data['is_share_customer'];
        $is_set_as_supplier = empty($addendum_data)? 0 : $addendum_data['is_set_as_supplier'];

        $is_in_experience = empty($addendum_data)? 0 : $addendum_data['is_in_experience'];
        $is_end_experience = empty($addendum_data)? 0 : $addendum_data['is_end_experience'];
        $album_amount = empty($addendum_data)? 0 : $addendum_data['album_amount'] + $setting_data['album_amount'];
        $album_page_amount = empty($addendum_data)? 0 : $addendum_data['album_page_amount'] + $setting_data['album_page_amount'];
        $empty_bill_amount = empty($addendum_data)? 0 : $addendum_data['empty_bill_amount'] + $setting_data['empty_bill_amount'];
        $special_seal = empty($addendum_data)? 0 : $addendum_data['special_seal'] + $setting_data['special_seal'];
        $one_key_album_times = empty($addendum_data)? 0 : $addendum_data['one_key_album_times'] + $setting_data['one_key_album_times'];
        $express_check_times = empty($addendum_data)? 0 : $addendum_data['express_check_times'] + $setting_data['express_check_times'];
        $clear_watermark_or_not = empty($addendum_data)? 0 : $addendum_data['clear_watermark_or_not'] + $setting_data['clear_watermark_or_not'];
        $file_total_size = empty($addendum_data)? 0 : $addendum_data['file_total_size'];

        $account_storage = empty($addendum_data['account_storage'])? $setting_data['account_storage'] : $addendum_data['account_storage'] + $setting_data['account_storage'];

        AdminAddendumModel::where('main_id', $main_id)->update([
            'main_id' => $main_id,
            'is_share_customer' => $is_share_customer,
            'is_set_as_supplier' => $is_set_as_supplier,
            'is_vip' => $is_vip,
            'vip_end_date' => $vip_end_date,
            'is_in_experience' => $is_in_experience,
            'is_end_experience' => $is_end_experience,
            'album_amount' => $album_amount,
            'album_page_amount' => $album_page_amount,
            'empty_bill_amount' => $empty_bill_amount,
            'special_seal' => $special_seal,
            'one_key_album_times' => $one_key_album_times,
            'express_check_times' => $express_check_times,
            'account_storage' => $account_storage,
            'clear_watermark_or_not' => $clear_watermark_or_not,
            'file_total_size' => $file_total_size,
            'is_first_charge' => 1,
            'first_charge_price' => $setting_data['first_charge_price'],
        ]);

        return true;
//        return AdminAddendumModel::updateOrCreate([
//            'main_id' => $main_id,
//        ],[
//
//
//        ]);
    }

    public static function updateSpaceOrderAddendum($main_id,$order_data)
    {
        $ss_time = 365*24*3600;
        $storage_end_date = "";
        $addendum_data = AdminAddendumModel::where(['main_id' => $main_id])->first();

        if(!empty($addendum_data['storage_end_date'])){

            if($addendum_data['storage_end_date'] > time()){
                //存储空间未到期，在原来的到期时间加一年。
                $storage_end_date = $addendum_data['storage_end_date'] + $ss_time;

            }else{
                //第一次购买、到期购买时间重新计算
                $storage_end_date = $order_data['pay_time'] + $ss_time;
            }

        }else{
            //第一次购买、到期购买时间重新计算
            $storage_end_date = $order_data['pay_time'] + $ss_time;
        }

        $account_storage = $addendum_data['account_storage'] + $order_data['buy_storage_space']*1024*1024;

        return AdminAddendumModel::where(['main_id' => $main_id])->update([
            'account_storage' => $account_storage,
            'storage_end_date' => $storage_end_date
        ]);
    }

}
